package juc.executors;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

public class CompletionServiceExample1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //futureDefect1();
        futureDefect2();

    }

    private static void futureDefect1() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Future<Integer> future = executorService.submit(() -> {
            timeSleep(20);
            return 10;
        });

        System.out.println("===");
        //拿结果时会阻塞，没有callback
        future.get();
    }

    private static void futureDefect2() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        final List<Callable<Integer>> callableList = Arrays.asList(
                () -> {
                    timeSleep(3);
                    System.out.println("the 1 finished");
                    return 1;
                }, () -> {
                    timeSleep(6);
                    System.out.println("the 2 finished");
                    return 2;
                });
        //List<Future<Integer>> futureList = executorService.invokeAll(callableList);
        //Integer v1 = futureList.get(0).get();
        //System.out.println(v1);
        //Integer v2 = futureList.get(1).get();
        //System.out.println(v2);

        List<Future<Integer>> futureList=new ArrayList<>();
        futureList.add(executorService.submit(callableList.get(0)));
        futureList.add(executorService.submit(callableList.get(1)));
        for (Future<Integer> future:futureList){
            System.out.println(future.get());
        }
    }

    /**
     * sleep the specify seconds
     */
    private static void timeSleep(long time) {
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
